<?php

namespace app\common\service;

use think\Exception;
use think\facade\Request;

/**
 * 微信二维码
 * Class WechatQrcodeService
 * @package app\common\service
 */
class WechatQrcodeService
{
    /**
     * 该方式必须要上线的小程序
     * @param $content
     * @param $page
     * @param $base_file
     * @return string
     * @throws Exception
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \WeChat\Exceptions\LocalCacheException
     */
    public static function create($content, $page , $base_file)
    {
        $config = [
            'appid' => config('wechat.miniapp.appid'),
            'appsecret' => config('wechat.miniapp.appsecret'),
        ];
        $qrcode = \We::WeMiniQrcode($config);
        $result = $qrcode->createMiniScene($content, $page);
        if (is_string($result)) {
            return self::createFile($result,$base_file);
        }
        throw new Exception(dump($result, false));
    }

    /**
     * 针对线下测试使用
     */
    public static function testCreate($page , $base_file)
    {
        $config = [
            'appid' => config('wechat.miniapp.appid'),
            'appsecret' => config('wechat.miniapp.appsecret'),
        ];
        $qrcode = \We::WeMiniQrcode($config);
        $result = $qrcode->createMiniPath($page);
        if (is_string($result)) {
            return self::createFile($result,$base_file);
        }
        throw new Exception(dump($result, false));
    }

    /**
     * 为二维码创建一个文件
     */
    protected static function createFile($content , $base_file = '')
    {
        $path = env('root_path') . 'public';
        $base_file =  $base_file ? : DS .'qrcode' . DS . date('Ym') . DS . uniqid('qrcode') . '.jpg';
        $filename = $path . $base_file;
        $remote   = Request::instance()->domain() . $base_file;
        if (!is_dir(dirname($filename))) {
            @mkdir(dirname($filename), 0755, true);
        }
        file_put_contents($filename, $content);
        return $remote;
    }
}